package com.uchedao.vehicledetection.utils;

import android.content.Context;
import android.os.AsyncTask;

import com.uchedao.vehicledetection.global.GlobalInfo;
import com.upyun.block.api.listener.CompleteListener;
import com.upyun.block.api.listener.ProgressListener;
import com.upyun.block.api.main.UploaderManager;
import com.upyun.block.api.utils.UpYunUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;

/**
 * Created by hang on 2015/9/22.
 */
public class UploadPicUtil {

    private String API_SECRET = "a3q6z6hheUR96OH7B08eDjtawwA=";
    // 空间名
    String bucket = "uchedao";

    private Context mContext;

    public UploadPicUtil(Context context) {
        this.mContext = context;
    }

//    public void upload(Photo[] photos, OnUploadListener listener) {
//        if(photos==null)
//            return;
//        new UploadTask(photos, listener).execute();
//    }
//
//    public class UploadTask extends AsyncTask<Void, Void, String> {
//        private Photo[] photos;
//        private OnUploadListener listener;
//        private int total;
//        private int completeCount;
//
//        public UploadTask(Photo[] photos, OnUploadListener listener) {
//            this.photos = photos;
//            this.listener = listener;
//            this.total = photos.length;
//            this.completeCount = 0;
//        }
//
//        @Override
//        protected String doInBackground(Void... params) {
//            for(final Photo p : photos) {
//                if(p == null) {
//                    total--;
//                    if(completeCount >= total) {
//                        // 图片全部上传完成
//                        if(listener != null)
//                            listener.onUpComplete();
//                        return "ok";
//                    }
//                    continue;
//                }
//
//                File localFile = new File(p.pic_path);
//                if(!localFile.exists() && listener!=null)
//                    listener.onFailed(p.name, p.pic_path, "该图片不存在", "NOT FOUND");
//
//                String picUrl = GlobalInfo.dbHelper.getPhotoFileId(p.pic_path);
//                if(picUrl == null) {
//                    // 本地未保存图片网络路径
//                    try {
//                        /*
//                         * 设置进度条回掉函数
//                         *
//                         * 注意：由于在计算发送的字节数中包含了图片以外的其他信息，最终上传的大小总是大于图片实际大小，
//                         * 为了解决这个问题，代码会判断如果实际传送的大小大于图片
//                         * ，就将实际传送的大小设置成'fileSize-1000'（最小为0）
//                         */
//                        ProgressListener progressListener = new ProgressListener() {
//                            @Override
//                            public void transferred(long transferedBytes, long totalBytes) {
//                                // do something...
////                            System.out.println("trans:" + transferedBytes + "; total:" + totalBytes);
//                                if(listener != null)
//                                    listener.onProgress(p.name, transferedBytes, totalBytes);
//                            }
//                        };
//
//                        CompleteListener completeListener = new CompleteListener() {
//                            @Override
//                            public void result(boolean isComplete, String result, String error) {
//                                // do something...
//                                System.out.println("isComplete:" + isComplete + ";result:" + result + ";error:" + error);
//                                if(!isComplete && listener!=null)
//                                    listener.onFailed(p.name, p.pic_path, result, error);
//
//                                if(isComplete) {
//                                    p.pic_url = Util.getFileName(p.pic_path);
//                                    // 图片网络路径保存本地
//                                    GlobalInfo.dbHelper.insertPhoto(p.pic_path, p.pic_url);
//                                }
//                                loadComplete();
//                            }
//                        };
//
//                        UploaderManager uploaderManager = UploaderManager.getInstance(bucket);
//                        uploaderManager.setConnectTimeout(60);
//                        uploaderManager.setResponseTimeout(60);
//                        Map<String, Object> paramsMap = uploaderManager.fetchFileInfoDictionaryWith(localFile, Util.getFileName(p.pic_path));
//                        //还可以加上其他的额外处理参数...
////                    paramsMap.put("return_url", "http://httpbin.org/get");
//                        // signature & policy 建议从服务端获取
//                        String policyForInitial = UpYunUtils.getPolicy(paramsMap);
//                        String signatureForInitial = UpYunUtils.getSignature(paramsMap, API_SECRET);
//                        uploaderManager.upload(policyForInitial, signatureForInitial, localFile, progressListener, completeListener);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                } else {
//                    p.pic_url = picUrl;
//                    loadComplete();
//                }
//            }
//            return "ok";
//        }
//
//        /**
//         * 判断图片是否全部上传完成
//         */
//        private void loadComplete() {
//            completeCount++;
//            if (completeCount >= total) {
//                if(listener != null)
//                    listener.onUpComplete();
//            }
//        }
//
//        @Override
//        protected void onPostExecute(String result) {
//            super.onPostExecute(result);
//        }
//    }
//
//    public interface OnUploadListener {
//        /**
//         * 进度
//         */
//        public void onProgress(String name, long transferedBytes, long totalBytes);
//
//        /**
//         * 单张图片失败
//         */
//        public void onFailed(String name, String path, String result, String error);
//
//        /**
//         * 完成(全部上传动作完成，无论成功失败)
//         */
//        public void onUpComplete();
//    }


    public void upSinglePic(String moduleName, String filePath, UpSinglePicCallback callback) {
        new UpSingleTask(moduleName, filePath, callback).execute();
    }

    public class UpSingleTask extends AsyncTask<Void, Void, String> {
        private String moduleName;
        private String filePath;
        private String fileUrl;
        private UpSinglePicCallback callback;

        public UpSingleTask(String moduleName, String filePath, UpSinglePicCallback callback) {
            this.moduleName = moduleName;
            this.filePath = filePath;
            this.callback = callback;
            fileUrl = "/"
                    + new SimpleDateFormat("yyyyMM").format(new Date())
                    + "/"
                    + System.currentTimeMillis()
                    + new Random().nextInt(9)
                    + Util.getFileName(filePath);
        }

        @Override
        protected String doInBackground(Void... params) {
                String picUrl = GlobalInfo.dbHelper.getPhotoFileId(filePath);
                if(picUrl == null) {
                    File localFile = new File(filePath);
                    if(!localFile.exists()) {
                        if(callback != null)
                            callback.uploadCallback(false, localFile.getName()+" not found", moduleName);
                        return "";
                    }

                    // 本地未保存图片网络路径
                    try {
                        ProgressListener progressListener = new ProgressListener() {
                            @Override
                            public void transferred(long transferedBytes, long totalBytes) {
                            }
                        };

                        CompleteListener completeListener = new CompleteListener() {
                            @Override
                            public void result(boolean isComplete, String result, String error) {
//                                System.out.println("isComplete:" + isComplete + ";result:" + result + ";error:" + error);
                                if(callback != null)
                                    callback.uploadCallback(isComplete, fileUrl, moduleName);
                                if(isComplete)
                                    GlobalInfo.dbHelper.insertPhoto(filePath, fileUrl);
                            }
                        };

                        UploaderManager uploaderManager = UploaderManager.getInstance(bucket);
                        uploaderManager.setConnectTimeout(60);
                        uploaderManager.setResponseTimeout(60);
                        Map<String, Object> paramsMap = uploaderManager.fetchFileInfoDictionaryWith(localFile, fileUrl);
                        paramsMap.put("x-gmkerl-quality", 70);
                        String policyForInitial = UpYunUtils.getPolicy(paramsMap);
                        String signatureForInitial = UpYunUtils.getSignature(paramsMap, API_SECRET);
                        uploaderManager.upload(policyForInitial, signatureForInitial, localFile, progressListener, completeListener);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    if(callback != null)
                        callback.uploadCallback(true, picUrl, moduleName);
                }
            return "ok";
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
        }
    }

    public interface UpSinglePicCallback {
        public void uploadCallback(boolean isSucceed, String result, String moduleName);
    }
}
